{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 线性回归的简洁实现\n",
    "\n",
    "随着深度学习框架的发展，开发深度学习应用变得越来越便利。实践中，我们通常可以用比上一节更简洁的代码来实现同样的模型。在本节中，我们将介绍如何使用MXNet提供的Gluon接口更方便地实现线性回归的训练。\n",
    "\n",
    "## 生成数据集\n",
    "\n",
    "我们生成与上一节中相同的数据集。其中`features`是训练数据特征，`labels`是标签。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "attributes": {
     "classes": [],
     "id": "",
     "n": "2"
    }
   },
   "outputs": [],
   "source": [
    "from mxnet import autograd, nd\n",
    "\n",
    "num_inputs = 2\n",
    "num_examples = 1000\n",
    "true_w = [2, -3.4]\n",
    "true_b = 4.2\n",
    "features = nd.random.normal(scale=1, shape=(num_examples, num_inputs))\n",
    "labels = true_w[0] * features[:, 0] + true_w[1] * features[:, 1] + true_b\n",
    "labels += nd.random.normal(scale=0.01, shape=labels.shape)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 读取数据集\n",
    "\n",
    "Gluon提供了`data`包来读取数据。由于`data`常用作变量名，我们将导入的`data`模块用添加了Gluon首字母的假名`gdata`代替。在每一次迭代中，我们将随机读取包含10个数据样本的小批量。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "attributes": {
     "classes": [],
     "id": "",
     "n": "3"
    }
   },
   "outputs": [],
   "source": [
    "from mxnet.gluon import data as gdata\n",
    "\n",
    "batch_size = 10\n",
    "# 将训练数据的特征和标签组合\n",
    "dataset = gdata.ArrayDataset(features, labels)\n",
    "# 随机读取小批量\n",
    "data_iter = gdata.DataLoader(dataset, batch_size, shuffle=True)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "这里`data_iter`的使用与上一节中的一样。让我们读取并打印第一个小批量数据样本。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "attributes": {
     "classes": [],
     "id": "",
     "n": "5"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "[[-0.88425034  1.1412233 ]\n",
      " [ 0.9561315  -0.8629183 ]\n",
      " [ 0.74419165  0.30639967]\n",
      " [ 0.9676651   0.5122743 ]\n",
      " [-0.1824717  -0.6532737 ]\n",
      " [-0.19343433 -0.4232046 ]\n",
      " [-1.1197332  -1.0690794 ]\n",
      " [-1.1318913   0.33254048]\n",
      " [ 0.6360805  -0.5844077 ]\n",
      " [-0.5839395  -0.19038047]]\n",
      "<NDArray 10x2 @cpu(0)> \n",
      "[-1.4545211   9.049869    4.6543612   4.405501    6.064423    5.259082\n",
      "  5.6068754   0.79540896  7.460776    3.688919  ]\n",
      "<NDArray 10 @cpu(0)>\n"
     ]
    }
   ],
   "source": [
    "for X, y in data_iter:\n",
    "    print(X, y)\n",
    "    break"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 定义模型\n",
    "\n",
    "在上一节从零开始的实现中，我们需要定义模型参数，并使用它们一步步描述模型是怎样计算的。当模型结构变得更复杂时，这些步骤将变得更烦琐。其实，Gluon提供了大量预定义的层，这使我们只需关注使用哪些层来构造模型。下面将介绍如何使用Gluon更简洁地定义线性回归。\n",
    "\n",
    "首先，导入`nn`模块。实际上，“nn”是neural networks（神经网络）的缩写。顾名思义，该模块定义了大量神经网络的层。我们先定义一个模型变量`net`，它是一个`Sequential`实例。在Gluon中，`Sequential`实例可以看作是一个串联各个层的容器。在构造模型时，我们在该容器中依次添加层。当给定输入数据时，容器中的每一层将依次计算并将输出作为下一层的输入。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "attributes": {
     "classes": [],
     "id": "",
     "n": "5"
    }
   },
   "outputs": [],
   "source": [
    "from mxnet.gluon import nn\n",
    "\n",
    "net = nn.Sequential()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "回顾图3.1中线性回归在神经网络图中的表示。作为一个单层神经网络，线性回归输出层中的神经元和输入层中各个输入完全连接。因此，线性回归的输出层又叫全连接层。在Gluon中，全连接层是一个`Dense`实例。我们定义该层输出个数为1。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "attributes": {
     "classes": [],
     "id": "",
     "n": "6"
    }
   },
   "outputs": [],
   "source": [
    "net.add(nn.Dense(1))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "值得一提的是，在Gluon中我们无须指定每一层输入的形状，例如线性回归的输入个数。当模型得到数据时，例如后面执行`net(X)`时，模型将自动推断出每一层的输入个数。我们将在之后“深度学习计算”一章详细介绍这种机制。Gluon的这一设计为模型开发带来便利。\n",
    "\n",
    "\n",
    "## 初始化模型参数\n",
    "\n",
    "在使用`net`前，我们需要初始化模型参数，如线性回归模型中的权重和偏差。我们从MXNet导入`init`模块。该模块提供了模型参数初始化的各种方法。这里的`init`是`initializer`的缩写形式。我们通过`init.Normal(sigma=0.01)`指定权重参数每个元素将在初始化时随机采样于均值为0、标准差为0.01的正态分布。偏差参数默认会初始化为零。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "attributes": {
     "classes": [],
     "id": "",
     "n": "7"
    }
   },
   "outputs": [],
   "source": [
    "from mxnet import init\n",
    "\n",
    "net.initialize(init.Normal(sigma=0.01))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 定义损失函数\n",
    "\n",
    "在Gluon中，`loss`模块定义了各种损失函数。我们用假名`gloss`代替导入的`loss`模块，并直接使用它提供的平方损失作为模型的损失函数。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "attributes": {
     "classes": [],
     "id": "",
     "n": "8"
    }
   },
   "outputs": [],
   "source": [
    "from mxnet.gluon import loss as gloss\n",
    "\n",
    "loss = gloss.L2Loss()  # 平方损失又称L2范数损失"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 定义优化算法\n",
    "\n",
    "同样，我们也无须实现小批量随机梯度下降。在导入Gluon后，我们创建一个`Trainer`实例，并指定学习率为0.03的小批量随机梯度下降（`sgd`）为优化算法。该优化算法将用来迭代`net`实例所有通过`add`函数嵌套的层所包含的全部参数。这些参数可以通过`collect_params`函数获取。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {
    "attributes": {
     "classes": [],
     "id": "",
     "n": "9"
    }
   },
   "outputs": [],
   "source": [
    "from mxnet import gluon\n",
    "\n",
    "trainer = gluon.Trainer(net.collect_params(), 'sgd', {'learning_rate': 0.03})"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 训练模型\n",
    "\n",
    "在使用Gluon训练模型时，我们通过调用`Trainer`实例的`step`函数来迭代模型参数。上一节中我们提到，由于变量`l`是长度为`batch_size`的一维`NDArray`，执行`l.backward()`等价于执行`l.sum().backward()`。按照小批量随机梯度下降的定义，我们在`step`函数中指明批量大小，从而对批量中样本梯度求平均。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {
    "attributes": {
     "classes": [],
     "id": "",
     "n": "10"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 1, loss: 0.040660\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 2, loss: 0.000151\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 3, loss: 0.000051\n"
     ]
    }
   ],
   "source": [
    "num_epochs = 3\n",
    "for epoch in range(1, num_epochs + 1):\n",
    "    for X, y in data_iter:\n",
    "        with autograd.record():\n",
    "            l = loss(net(X), y)\n",
    "        l.backward()\n",
    "        trainer.step(batch_size)\n",
    "    l = loss(net(features), labels)\n",
    "    print('epoch %d, loss: %f' % (epoch, l.mean().asnumpy()))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "下面我们分别比较学到的模型参数和真实的模型参数。我们从`net`获得需要的层，并访问其权重（`weight`）和偏差（`bias`）。学到的参数和真实的参数很接近。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {
    "attributes": {
     "classes": [],
     "id": "",
     "n": "12"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "([2, -3.4], \n",
       " [[ 1.9999468 -3.4000072]]\n",
       " <NDArray 1x2 @cpu(0)>)"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "dense = net[0]\n",
    "true_w, dense.weight.data()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {
    "attributes": {
     "classes": [],
     "id": "",
     "n": "13"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(4.2, \n",
       " [4.1993876]\n",
       " <NDArray 1 @cpu(0)>)"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "true_b, dense.bias.data()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 小结\n",
    "\n",
    "* 使用Gluon可以更简洁地实现模型。\n",
    "* 在Gluon中，`data`模块提供了有关数据处理的工具，`nn`模块定义了大量神经网络的层，`loss`模块定义了各种损失函数。\n",
    "* MXNet的`initializer`模块提供了模型参数初始化的各种方法。\n",
    "\n",
    "\n",
    "## 练习\n",
    "\n",
    "* 如果将`l = loss(net(X), y)`替换成`l = loss(net(X), y).mean()`，我们需要将`trainer.step(batch_size)`相应地改成`trainer.step(1)`。这是为什么呢？\n",
    "* 查阅MXNet文档，看看`gluon.loss`和`init`模块里提供了哪些损失函数和初始化方法。\n",
    "* 如何访问`dense.weight`的梯度？\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "## 扫码直达[讨论区](https://discuss.gluon.ai/t/topic/742)\n",
    "\n",
    "![](../img/qr_linear-regression-gluon.svg)"
   ]
  }
 ],
 "metadata": {
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}